package com.tools.cleanmaster.ui.base;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.PopupWindow;

import com.nineoldandroids.animation.Animator;
import com.nineoldandroids.animation.AnimatorListenerAdapter;
import com.nineoldandroids.animation.ValueAnimator;
import com.swipe.SwipeMgr;
import com.tools.ad.EntranceType;
import com.tools.ad.adscene.AdScene;
import com.tools.ad.util.GARecordUtils;
import com.tools.ad.util.StatusBarUtil;
import com.tools.cleanmaster.BuildConfig;
import com.tools.cleanmaster.CleanApplication;
import com.tools.cleanmaster.CleanGAConstant;
import com.tools.cleanmaster.R;
import com.tools.cleanmaster.bean.AutoCleanFeature;
import com.tools.cleanmaster.functionpage.FunctionItem;
import com.tools.cleanmaster.manager.AutoCleanManager;
import com.tools.cleanmaster.scenenew.SceneType;
import com.tools.cleanmaster.store.ResultPageSharedPrefManager;
import com.tools.cleanmaster.ui.activity.AboutActivity;
import com.tools.cleanmaster.ui.activity.AutoCleanSettingActivity;
import com.tools.cleanmaster.ui.activity.ChargingSettingActivity;
import com.tools.cleanmaster.ui.activity.CleanerActivity;
import com.tools.cleanmaster.ui.activity.SwipeSettingActivity;
import com.tools.cleanmaster.ui.card.ACardItem;
import com.tools.cleanmaster.ui.card.TrashCardItem;
import com.tools.cleanmaster.ui.card.TrashCardListener;
import com.tools.cleanmaster.ui.card.animator.AnimationListenerAdapter;
import com.tools.cleanmaster.ui.card.factory.CardDataHelper;
import com.tools.cleanmaster.ui.card.factory.CardListAdapter;
import com.tools.cleanmaster.ui.card.ui.ResultMultiCardLayout;
import com.tools.cleanmaster.ui.card.ui.ResultSingleCardLayout;
import com.tools.cleanmaster.ui.card.ui.SpringRopeView;
import com.tools.cleanmaster.ui.view.header.Header;
import com.tools.cleanmaster.ui.view.quickaction.ActionItem;
import com.tools.cleanmaster.ui.view.quickaction.QuickPopupWindow;
import com.tools.cleanmaster.utils.FeatureConfig;

import java.util.Iterator;
import java.util.List;

/**
 * 结果页基类-显示各种操作后的结果页面（例如，清理后显示的结果需要继承于这个类）
 * Created by wen.yu.gang on 18/6/26.
 */
public abstract class ResultSingleActivity extends SingleActivity {
    private static final int RISE_CARD_AREA_ANIMATION_DURATION = 200;
    /**
     * 结果内容容器
     */
    private FrameLayout mResultPageWrapper;
    /**
     * 多卡片布局
     */
    protected ResultMultiCardLayout mResultMultiCardLayout;
    /**
     * 单个卡片布局
     */
    protected ResultSingleCardLayout mResultSingleCardLayout;

    private View mListViewHeader;
    protected Bundle resultPageData = new Bundle();
    protected SpringRopeView mRope;
    protected CardListAdapter mCardListAdapter;

    private ResultMultiCardLayout.ResultCardAnimListener mCardAnimationListener;
    /**
     * 弹出结果布局的动画
     */
    private ValueAnimator mPopResultAnimator;
    private long mResultPageShowTimeStampForReport;
    protected View mHeadTitle;

    //记录扫描结束时间
    protected long mIntervalTime = 0;
    private long mLastPopWindowDismissTime = -1;
    protected QuickPopupWindow mSettingMenu = null;
    protected boolean mIsPopMenuShow = false;
    protected Header mHeader;
    protected View mSettingView;
    protected View mAdView;

    protected abstract void setCardHeadTitle();

    protected abstract void hideBackground();

    protected abstract EntranceType getEntranceType();

    public abstract ResultPageType getResultPageType();

    protected void resultPageShowFinish() {
    }

    public enum ResultPageType {
        SingleCardPage, MultiCardPage, NoPage
    }

    protected void reportShow() {

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(savedInstanceState);
        StatusBarUtil.setTransparent(this);
        initCardView();
    }

    @Override
    protected void doOnResume() {
        if (mCardListAdapter != null && getResultPageType().equals(ResultPageType.MultiCardPage)) {
            mCardListAdapter.onActivityResume();
        }
        if (mResultSingleCardLayout != null && getResultPageType().equals(ResultPageType.SingleCardPage)) {
            mResultSingleCardLayout.onActivityResume();
        }
    }

    @Override
    protected void doOnPause() {
        //上报结果页停留时间
        if (mResultPageShowTimeStampForReport > 0) {
            long currentTime = System.currentTimeMillis();
            long stayTime = System.currentTimeMillis() - mResultPageShowTimeStampForReport;
            if (FeatureConfig.DEBUG_LOG) {
                if (currentTime - stayTime < 0) {
                    throw new RuntimeException("结果页上报停留时间出错，currentTime=" + currentTime + ", resultPageShowTime=" + mResultPageShowTimeStampForReport);
                }
            }
            mResultPageShowTimeStampForReport = 0;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mCardListAdapter != null) {
            mCardListAdapter.onActivityDestroy();
        }
        if (mResultSingleCardLayout != null) {
            mResultSingleCardLayout.onActivityDestroy(getBaseContext());
        }
        mAdView = null;
    }

    protected abstract void setContentView(Bundle savedInstanceState);

    protected void setLastCleanSize() {
    }

    // 主动扫描入口的单卡结果页
    protected void startSingleCardResultAnim() {
        if (mResultSingleCardLayout == null) {
            initCardView();
        }
        hideBackground();
        ViewGroup adLayout = mResultSingleCardLayout.findViewById(R.id.advert_container);
        adLayout.setVisibility(View.INVISIBLE);

        mResultSingleCardLayout.setVisibility(View.VISIBLE);
        mResultSingleCardLayout.initResultPageUI();
        mResultSingleCardLayout.startRecommendCardAnimation();
        setCardHeadTitle();

        LinearLayout resultTitle = mResultSingleCardLayout.findViewById(R.id.result_title);
        resultTitle.startAnimation(resultPageAnim(adLayout));
    }

    // 场景化入口的单卡结果页
    protected void startSingleCardSceneAnim(SceneType type, Bundle data) {
        if (mResultSingleCardLayout == null) {
            initCardView();
        }
        reportShow();
        ViewGroup adLayout = mResultSingleCardLayout.findViewById(R.id.advert_container);
        adLayout.setVisibility(View.INVISIBLE);

        mResultSingleCardLayout.setVisibility(View.VISIBLE);
        mResultSingleCardLayout.initSceneUI(type, data);

        AdScene advertScene = imContext.getADModule().getAdSceneManager().getAdScene(getEntranceType());
        View adView = advertScene.getAdView();
        if (adView != null) {
            mResultSingleCardLayout.fillADView(adView);
        }

        LinearLayout resultTitle = mResultSingleCardLayout.findViewById(R.id.result_title);
        resultTitle.startAnimation(resultPageAnim(adLayout));
    }

    // 首页功能入口的单卡结果页
    protected void startSingleCardFunctionItemAnim(FunctionItem type, Bundle data) {
        if (mResultSingleCardLayout == null) {
            initCardView();
        }

        mResultSingleCardLayout.setVisibility(View.VISIBLE);
        mResultSingleCardLayout.initFunctionUI(type, data);

        ViewGroup adLayout = mResultSingleCardLayout.findViewById(R.id.advert_container);
        if (mAdView != null) {
            adLayout.removeAllViews();
            adLayout.addView(mAdView);
        }

        LinearLayout resultTitle = mResultSingleCardLayout.findViewById(R.id.result_title);
        resultTitle.startAnimation(resultPageAnim(adLayout));
    }

    protected Animation resultPageAnim(final ViewGroup adLayout) {
        Animation anim = AnimationUtils.loadAnimation(this, R.anim.new_result_page_left_in);
        final Animation bottomInAnimation = AnimationUtils.loadAnimation(this, R.anim.new_result_page_bottom_in);
        bottomInAnimation.setAnimationListener(new AnimationListenerAdapter());
        anim.setAnimationListener(new AnimationListenerAdapter() {
            @Override
            public void onAnimationEnd(Animation animation) {
                adLayout.setVisibility(View.VISIBLE);
                adLayout.startAnimation(bottomInAnimation);
                resultPageShowFinish();
            }
        });
        return anim;
    }

    // 开始卡片动画
    protected void startMultiCardAnim() {
        if (mResultMultiCardLayout == null) {
            initCardView();
        }
        setCardHeadTitle();
        hideBackground();
        setLastCleanSize();

        mHeadTitle.setVisibility(View.VISIBLE);

        //设置结果页首次进入时间
        long firstTime = ResultPageSharedPrefManager.getResultFirstShowTime(CleanApplication.getInstance());
        if (firstTime == 0) {
            ResultPageSharedPrefManager.setResultFirstShowTime(CleanApplication.getInstance());
        }

        mResultPageShowTimeStampForReport = System.currentTimeMillis();

        cardScan();

        if (mRope.getVisibility() == View.GONE) {
            mRope.setVisibility(View.VISIBLE);
        }
        if (mListViewHeader.getVisibility() == View.VISIBLE) {
            mListViewHeader.setVisibility(View.INVISIBLE);
        }
        if (mResultMultiCardLayout != null) {
            mResultMultiCardLayout.setHeaderChildViewInvisible();
        }

        mCardAnimationListener = new ResultMultiCardLayout.ResultCardAnimListener() {
            @Override
            public void onAllAnimationStart() {
            }

            @Override
            public void onHeaderAnimationStart() {
            }

            @Override
            public void onAllAnimationEnd() {
                mHeadTitle.setVisibility(View.INVISIBLE);
                onCleanResultAllAnimationEnd();
            }
        };

        mPopResultAnimator = ValueAnimator.ofFloat(1, 0);
        mPopResultAnimator.setDuration(RISE_CARD_AREA_ANIMATION_DURATION);
        mPopResultAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            private boolean mDampingStarted = false;

            @Override
            public void onAnimationUpdate(ValueAnimator anim) {
                float animProgress = (Float) anim.getAnimatedValue();
                int topMargin = (int) (2000 * animProgress);
                setResultAreaTopMargin(topMargin);
                if (animProgress < 0.1f) {
                    if (!mDampingStarted) {
                        mRope.post(new Runnable() {

                            @Override
                            public void run() {
                                mRope.startSpring();
                            }
                        });
                        mDampingStarted = true;
                    }
                } else {
                    mRope.setSpringPosition(animProgress);
                }

            }
        });

        mPopResultAnimator.addListener(new AnimatorListenerAdapter() {

            @Override
            public void onAnimationStart(Animator animation) {
                if (mResultMultiCardLayout != null) {
                    mResultMultiCardLayout.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            mResultMultiCardLayout.setCardAdapterWithAnim(mCardListAdapter, mCardAnimationListener);
                        }
                    }, 0);
                }
            }

            @Override
            public void onAnimationEnd(Animator animation) {
            }

        });
        mPopResultAnimator.start();
        mRope.addAnimationListener(new SpringRopeView.AnimationListener() {
            @Override
            public void onAnimationCompleted() {
                mRope.clearAnimation();
                mRope.setVisibility(View.GONE);
                if (mResultMultiCardLayout != null) {
                    mResultMultiCardLayout.setVisibility(View.VISIBLE);
                    resultPageShowFinish();
                }
            }
        });
    }

    protected void onCleanResultAllAnimationEnd() {

    }

    /**
     * 初始化卡片相关UI
     */
    private void initCardView() {
        mResultPageWrapper = findViewById(R.id.card_wrapper);
        ViewGroup.LayoutParams wrapperParams = mResultPageWrapper.getLayoutParams();
        switch (getResultPageType()) {
            case MultiCardPage:
                initMultiCardResultLayout(wrapperParams);
                break;
            case SingleCardPage:
                initSingleCardResultLayout(wrapperParams);
                break;
            default:
                break;
        }
        mRope = findViewById(R.id.spring);
        mHeadTitle = findViewById(R.id.head_title);
    }

    /**
     * 多卡片结果布局
     *
     * @param wrapperParams
     */
    protected void initMultiCardResultLayout(ViewGroup.LayoutParams wrapperParams) {
        mResultMultiCardLayout = new ResultMultiCardLayout(this);
        mResultPageWrapper.addView(mResultMultiCardLayout);
        FrameLayout.LayoutParams resultCardParams = (FrameLayout.LayoutParams) mResultMultiCardLayout.getLayoutParams();
        resultCardParams.height = wrapperParams.height;
        resultCardParams.width = wrapperParams.width;
        mResultMultiCardLayout.setLayoutParams(resultCardParams);
        mResultMultiCardLayout.setVisibility(View.INVISIBLE);
        mListViewHeader = LayoutInflater.from(CleanApplication.getInstance()).inflate(R.layout.card_header, null);
        mListViewHeader.setVisibility(View.INVISIBLE);
        mResultMultiCardLayout.setHeaderView(mListViewHeader);
        View rootContent = findViewById(R.id.root_content);
        if (rootContent != null) {
            rootContent.setBackgroundColor(getResources().getColor(R.color.title_background));
        }
    }

    /**
     * 无卡片布局
     *
     * @param wrapperParams
     */
    protected void initSingleCardResultLayout(ViewGroup.LayoutParams wrapperParams) {
        mResultSingleCardLayout = new ResultSingleCardLayout(this);
        mResultPageWrapper.addView(mResultSingleCardLayout);
        FrameLayout.LayoutParams newResultCardParams = (FrameLayout.LayoutParams) mResultSingleCardLayout.getLayoutParams();
        newResultCardParams.height = wrapperParams.height;
        newResultCardParams.width = wrapperParams.width;
        mResultSingleCardLayout.setLayoutParams(newResultCardParams);
        mResultSingleCardLayout.setVisibility(View.INVISIBLE);
    }

    // 背景开始上移
    private void setResultAreaTopMargin(int topMargin) {
        if (mRope != null) {
            ViewGroup.MarginLayoutParams lp = (ViewGroup.MarginLayoutParams) mRope.getLayoutParams();
            lp.topMargin = topMargin;
            mRope.setLayoutParams(lp);
        }
    }

    // 获取卡片列表
    private void cardScan() {
        CardDataHelper cardDataHelper = new CardDataHelper(getEntranceType());
        List<ACardItem> cardItems = cardDataHelper.produceCards();
        Iterator<ACardItem> listIterator = cardItems.listIterator();
        while (listIterator.hasNext()) {
            ACardItem cardItem = listIterator.next();
            if (cardItem instanceof TrashCardItem) {
                ((TrashCardItem) cardItem).setTrashListener(getTrashCardListener());
            }
        }

        mCardListAdapter = new CardListAdapter(ResultSingleActivity.this, mResultMultiCardLayout.getCardListView(), cardItems, getEntranceType());
    }

    protected TrashCardListener getTrashCardListener() {
        return null;
    }

    protected int getSceneType() {
        return -1;
    }

    /**
     * 菜单
     *
     * @param v
     */
    protected void popupMenu(final View v) {
        if (System.currentTimeMillis() - mLastPopWindowDismissTime < POPWINDOW_SHOW_TWICE_INTERVAL) {
            return;
        }
        if (mIsPopMenuShow) {
            return;
        }

        GARecordUtils.report(imContext, CleanGAConstant.C_FUNC, CleanGAConstant.A_CLICK, CleanGAConstant.L_HOME_MENU);

        mSettingMenu = new QuickPopupWindow(v);

        //自动缓存与内存清理优化设置页
        final ActionItem autoCleanItem = new ActionItem();
        autoCleanItem.setTitle(getString(R.string.item_card_smart_clean_title));
        autoCleanItem.setShowNewTip(!AutoCleanFeature.AUTO_CACHE.isEnable() && !AutoCleanFeature.AUTO_MEMORY.isEnable());
        autoCleanItem.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mSettingMenu.dismiss();
                GARecordUtils.report(imContext, CleanGAConstant.C_FUNC, CleanGAConstant.A_CLICK, CleanGAConstant.L_HOME_MENU_SMART_CLEAN);
                Intent intent = new Intent(ResultSingleActivity.this, AutoCleanSettingActivity.class);
                intent.putExtra(AutoCleanSettingActivity.FROM_EXTRA, AutoCleanManager.FROM_MENU);
                startActivityWithAnim(intent);
            }
        });
        mSettingMenu.addActionItem(autoCleanItem);

        // swipe
        try {
            if (imContext.getADModule().isOrganicOrOtherChannel() && SwipeMgr.getInstance().isSwipeEnable()) {
                final ActionItem swipe = new ActionItem();
                swipe.setTitle(getString(R.string.du_swipe_settting_title));
                swipe.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        mSettingMenu.dismiss();
                        Intent intent = new Intent(ResultSingleActivity.this, SwipeSettingActivity.class);
                        startActivityWithAnim(intent);
                    }
                });
                mSettingMenu.addActionItem(swipe);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        // 充电屏保
        final ActionItem chargingItem = new ActionItem();
        chargingItem.setTitle(getString(R.string.charge_status_title));
        chargingItem.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mSettingMenu.dismiss();
                GARecordUtils.report(imContext, CleanGAConstant.C_FUNC, CleanGAConstant.A_CLICK, CleanGAConstant.L_HOME_MENU_SMART_CHARGE);
                Intent intent = new Intent(ResultSingleActivity.this, ChargingSettingActivity.class);
                startActivityWithAnim(intent);
            }
        });
        mSettingMenu.addActionItem(chargingItem);

        // feedback
        final ActionItem feed = new ActionItem();
        feed.setTitle(getString(R.string.opda_global_feed));
        feed.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mSettingMenu.dismiss();
                GARecordUtils.report(imContext, CleanGAConstant.C_FUNC, CleanGAConstant.A_CLICK, CleanGAConstant.L_HOME_MENU_FEEDBACK);
                Intent i = new Intent(Intent.ACTION_SENDTO);
                i.setData(Uri.parse("mailto:" + BuildConfig.FEEDBACK_MAIL));
                i.putExtra(Intent.EXTRA_SUBJECT, getString(R.string.opda_global_feed));
                try {
                    startActivity(i);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
        mSettingMenu.addActionItem(feed);

        // About
        final ActionItem about = new ActionItem();
        about.setTitle(getString(R.string.opda_global_about));
        about.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mSettingMenu.dismiss();
                GARecordUtils.report(imContext, CleanGAConstant.C_FUNC, CleanGAConstant.A_CLICK, CleanGAConstant.L_HOME_MENU_ABOUT);
                Intent intent = new Intent(ResultSingleActivity.this, AboutActivity.class);
                startActivity(intent);
            }
        });
        mSettingMenu.addActionItem(about);

        mSettingMenu.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                mIsPopMenuShow = false;
                mLastPopWindowDismissTime = System.currentTimeMillis();
            }
        });

        // Test
        if (BuildConfig.DEBUG || imContext.getCleanSharedPrefManager().getKeyOpenDeveloper()) {
            final ActionItem testItem = new ActionItem();
            testItem.setTitle("Test");
            testItem.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    mSettingMenu.dismiss();
                    Intent intent = new Intent(ResultSingleActivity.this, CleanerActivity.class);
                    startActivity(intent);
                }
            });
            mSettingMenu.addActionItem(testItem);
        }


        mSettingMenu.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                mIsPopMenuShow = false;
                mLastPopWindowDismissTime = System.currentTimeMillis();
            }
        });

        mIsPopMenuShow = true;
        mSettingMenu.show();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_MENU) {
            if (mIsPopMenuShow && mSettingMenu != null) {
                mSettingMenu.dismiss();
            } else if (mSettingView != null) {
                popupMenu(mSettingView);
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    /**
     * 当前是否显示结果页
     *
     * @return
     */
    protected boolean isResultShow() {
        if (mResultMultiCardLayout != null) {
            return mResultMultiCardLayout.getVisibility() == View.VISIBLE;
        }
        if (mResultSingleCardLayout != null) {
            return mResultSingleCardLayout.getVisibility() == View.VISIBLE;
        }
        return false;
    }
}
